#!/bin/sh /etc/rc.common
# Copyright (C) 2019-2020 Lienol <lawlienol@gmail.com>

START=99

CONFIG=trojan_server
CONFIG_PATH=/var/etc/$CONFIG
LOG_PATH=/var/log/$CONFIG
LOG_APP_FILE=$LOG_PATH/app.log

echolog() {
	echo -e "$(date "+%Y-%m-%d %H:%M:%S"): $1" >> $LOG_APP_FILE
}

gen_trojan_config_file() {
	config_get enable $1 enable
	[ "$enable" = "0" ] && return 0
	config_get remarks $1 remarks
	config_get port $1 port
	config_get ssl_certFile $1 ssl_certFile
	config_get ssl_keyFile $1 ssl_keyFile
	[ ! -f "$ssl_certFile" ] && echolog "$remarks $port 找不到HTTPS公钥文件，运行失败！" && exit 
	[ ! -f "$ssl_keyFile" ] && echolog "$remarks $port 找不到HTTPS私钥文件，运行失败！" && exit 
	lua /usr/lib/lua/luci/model/cbi/trojan_server/api/gen_trojan_config_file.lua $1 > $CONFIG_PATH/$1.json
	echolog "$remarks $port 生成并运行 Trojan 配置文件 - $CONFIG_PATH/$1.json" 
	trojan -c $CONFIG_PATH/$1.json >/dev/null 2>&1 &
}

start_trojan_server() {
	mkdir -p $CONFIG_PATH $LOG_PATH
	touch $LOG_APP_FILE
	config_foreach gen_trojan_config_file "user"
	fw3 reload >/dev/null 2>&1 &
}

stop_trojan_server() {
	fw3 reload >/dev/null 2>&1 &
	ps -w | grep "$CONFIG_PATH/" | grep -v "grep" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	rm -rf $CONFIG_PATH
	rm -rf $LOG_PATH
}

start() {
	config_load $CONFIG
	enable=$(uci get $CONFIG.@global[0].enable)
	if [ "$enable" = "0" ];then
		stop_trojan_server
	else
		start_trojan_server
	fi
}

stop() {
	stop_trojan_server
}

restart() {
	stop
	sleep 1
	start
}